package com.apexedu.portal.service.impl;

import com.apexedu.biz.Const;
import com.apexedu.biz.entity.TAccessAppReg;
import com.apexedu.framework.service.impl.AbstractBaseServiceSupport;
import com.apexedu.framework.util.DBUtil;
import com.apexedu.framework.util.Pager;
import com.apexedu.framework.util.SeqFactory;
import com.apexedu.identity.entity.TSysRole;
import com.apexedu.portal.action.AppRoleSetAction;
import com.apexedu.portal.action.PortalRoleTodoAction;
import com.apexedu.portal.entity.AppFunctionConfig;
import com.apexedu.portal.entity.AppRoleFunction;
import com.apexedu.portal.entity.TLbxx;
import com.apexedu.portal.entity.TSysRoleWorkflow;
import com.apexedu.util.StringUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 移动校园权限设置
 * Created by janabo on 2014-12-9.
 */
@Service("appRoleSetService")
public class AppRoleSetServiceImpl extends AbstractBaseServiceSupport {

    @Override
    public void saveOrUpdate(Object o) throws Exception {

    }

    @Override
    public List<TSysRole> list(Object o, Pager pager) throws Exception {
        AppRoleSetAction action = (AppRoleSetAction) o;
        //表示新增还是修改
        String flag = action.getParameter("flag");
        //得到系统编号
        String appid = action.getParameter("appid");
        //得到存在的角色
        String roleids = action.getParameter("rolesId");
        String menues = action.getParameter("menues");
        if (StringUtil.isNotBlank(flag)) {
            String[] workflows = menues.split(",");
            String[] roles = roleids.split(",");
            List<AppRoleFunction> todos = new ArrayList<AppRoleFunction>();
            for(int i=0;i<roles.length;i++){
                String roleid = roles[i];
                if("".equals(roleid)){
                    continue;
                }
                for(int j=0;j<workflows.length;j++){
                    String todoid = workflows[j];
                    int count =DBUtil.count("select count(*) from APP_ROLE_FUNCTION t where t.roleid = ? and t.functionid =?",roleid,todoid);
                    if(count>0){
                        continue;
                    }
                    AppRoleFunction tRoleWorkflow = new AppRoleFunction();
                    tRoleWorkflow.setWid(SeqFactory.getNewSequenceAlone());
                    tRoleWorkflow.setRoleid(roleid);
                    tRoleWorkflow.setFunctionid(todoid);
                    todos.add(tRoleWorkflow);
                }
            }
            baseDao.saveAll(todos);
            action.setMsg("保存成功！");
        }
        List<TAccessAppReg> list = queryAllMenu();
        if (StringUtil.isNotBlank(appid)) {
            int appno = 0;
            //根据appid得到对应的下标
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getAppid().equals(appid)) {
                    appno = i;
                    break;
                }
            }
            action.setAppno(appno);
        }
        //查询出所有业务系统中所有拥有门户资源的角色
        String sql = "select distinct(roleid) as roleid from APP_ROLE_FUNCTION t";
        List<AppRoleFunction> roleWorkflows = DBUtil.queryAllBeanList(sql, AppRoleFunction.class);

        StringBuffer roles = new StringBuffer();
        //角色id拼装成字符串
        for (int i = 0; i < roleWorkflows.size(); i++) {
            roles.append(",");
            roles.append(roleWorkflows.get(i).getRoleid());
        }
        action.setParameter("appid", appid);
        action.setParameter("roles", roles);
        action.setParameter("rolesId", roleids);
        //业务系统列表
        action.setListApp(list);
        return null;
    }

    @Override
    public boolean remove(Object o) throws Exception {
        return false;
    }

    /**
     * 查询所有的系统名称
     *
     * @return List<TAccessAppReg>
     */
    public List<TAccessAppReg> queryAllMenu() {
        String sql = "select appid ,appname from T_ACCESS_APP_REG where state=1 order by ordernum desc,appid";
        List<TAccessAppReg> list = DBUtil.queryAllBeanList(sql, TAccessAppReg.class);
        return list;
    }

    /**
     * 查询所有业务系统下对应的角色
     */
    public List<TSysRole> queryAllRole(String appid, String appno) {
        List<TAccessAppReg> appRegs = queryAllMenu();
        if (StringUtil.isBlank(appid) && StringUtil.isBlank(appno)) {
            try {
                appid = appRegs.get(0).getAppid();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (StringUtil.isNotBlank(appno)) {
            appid = appRegs.get(Integer.parseInt(appno)).getAppid();
        }
        String sql = "select roleid,rolename from T_SYS_ROLE where belongtoapp =?";
        List<TSysRole> list = DBUtil.queryAllBeanList(sql, TSysRole.class, appid);
        return list;
    }

    /**
     * 查询所有的app选项卡
     * @return
     */
    public List<AppFunctionConfig> queryAllAppTab(){
        List<AppFunctionConfig> plist = DBUtil.queryAllBeanList("select * from APP_FUNCTION_CONFIG t where t.superid = '0' order by style,orderno", AppFunctionConfig.class);
        List<AppFunctionConfig> clist = DBUtil.queryAllBeanList("select * from APP_FUNCTION_CONFIG t where t.superid != '0' order by style,orderno",AppFunctionConfig.class);
        List<AppFunctionConfig> list = new ArrayList<AppFunctionConfig>();
        for(AppFunctionConfig p : plist){
            list.add(p);
            for(AppFunctionConfig c : clist){
                if(p.getId().equals(c.getSuperid())){
                    list.add(c);
                }
            }
        }
        return list;
    }

    @Override
    public void load(Object o) throws Exception {
        AppRoleSetAction action = (AppRoleSetAction) o;
        //获取角色id
        String roleid = action.getParameter("wid");
        String roleids = action.getParameter("roleid");
        String hql = "from TSysRole r where r.roleid = ?";
        if (StringUtil.isBlank(roleid) && StringUtil.isNotBlank(roleids)) {
            roleid = roleids;
        }
        //通过wid得到角色
        TSysRole tsysRole = getBaseDao().findFieldValue(hql, roleid);
        action.setTsysRole(tsysRole);

        String sql = "select * from APP_ROLE_FUNCTION t where t.roleid = ?";
        //查询出所有角色对应的资源
        List<AppRoleFunction> roleMenus = DBUtil.queryAllBeanList(sql, AppRoleFunction.class,roleid);
        StringBuffer roleMenusBuffer = new StringBuffer();
        for (int i = 0; i < roleMenus.size(); i++) {
            roleMenusBuffer.append(roleMenus.get(i).getFunctionid());
            if (i < roleMenus.size() - 1) {
                roleMenusBuffer.append(",");
            }
        }
        action.setParameter("roleid", roleid);
        action.setParameter("roleMenusBuffer", roleMenusBuffer);
        List<AppFunctionConfig> list = queryAllAppTab();
        action.setParameter("lbxxlist", list);
        action.setParameter("portalname", "门户资源");
    }

    //点击角色保存资源
    public String saveRoleMenu(String roleid, String menus) {
        String[] workflows = menus.split(",");
        List<AppRoleFunction> todos = new ArrayList<AppRoleFunction>();
        DBUtil.executeSQL("delete from APP_ROLE_FUNCTION t where t.roleid = ?",roleid);
        for(int j=0;j<workflows.length;j++){
            String todoid = workflows[j];
            AppRoleFunction tRoleWorkflow = new AppRoleFunction();
            tRoleWorkflow.setWid(SeqFactory.getNewSequenceAlone());
            tRoleWorkflow.setRoleid(roleid);
            tRoleWorkflow.setFunctionid(todoid);
            todos.add(tRoleWorkflow);
        }
        baseDao.saveAll(todos);
        //保存成功
        return Const.MESSAGE_SAVE_SUCCESS;
    }
}
